Skip to main content

Example: Replacing leading and trailing characters in a string

Sequencing principles demonstrated

An extension (a problem solving sequence) which includes a variation (a problem solving sequence).

Prerequisite content

Prior to asking the learner to solve a problem, the following content is provided.

The following code prints each character, one-by-one, in a string. The code illustrates traversing a string in the forward direction using a for loop.

for (int i = 0; i < txt.length(); i++)
cout << str[i] // Display the character at position i

Illustrates traversing a string in the backward direction using a for loop.

for (int i = txt.length() - 1; i >= 0; i--)
cout << str[i] // Display the character at position i

Find the first occurence of "n" in a string

The following code illustrates using a while loop that runs while two conditions are true. One of them is while the end of the string has not been reached, which is common.

i = 0;
while (index < str.length() && str[index] <> 'n')
i++;
if (str[index] <> 'n')
pos = i;
else:
pos = -1; // "n" not found

Problem

Replace all leading and trailing spaces in a string with the - character.

Solution

index = 0
while (index < len(str.length() && string[index] == " ")
{
str[index] = "-";
index++;
}
index = len(string) - 1
while (index >= 0 && string[index] == " ") {
str[index] = "-";
index--;
}

Sequencing analysis of the solution

The solution uses an extension, which includes a variation.

The extension

Two loops are needed. One traverses forward. The other traverses backward. The background info. did not give an example of using two loops in the same program.

The variation

The background info used while (index < str.length() && str[index] <> 'n'). In the solution, while (index < str.length() && string[index] == " ") is a variation of that.